import { useCallback, useEffect, useState } from 'react';
// 如果没有rbac模块的话；用下面的login 和 getUserBaseInfo方法
import { getUserBaseInfo, captcha, login } from '@services/base-layout-service';
import { getRealMenuList, setStorage, clearStorage, getFrontCodeListForAdmin } from '@biz/index';
import md5 from '@utils/md5';
import { useNavigate } from 'react-router-dom';
import { uiData } from '@/store';
import to from 'await-to-js';

const getFirstPagePath = (menuList) => {
    const getPathFromArr = (list) => {
        let targetPath = '';
        if (Array.isArray(list)) {
            for (let i = 0, len = list.length; i < len; i++) {
                const item = list[i];
                if (item.path) {
                    targetPath = item.path;
                    if (Array.isArray(item.breadcrumb)) {
                        uiData.updateBreadcrumb(item.breadcrumb);
                    }
                    return targetPath;
                } else if (item.children && item.children.length > 0) {
                    return getPathFromArr(item.children);
                }
            }
        }

        return targetPath;
    };

    return getPathFromArr(menuList);
};

function useLogin(form) {
    const navigate = useNavigate();
    const [captchaImg, setCaptchaImg] = useState('');
    const [captchaObj, setCaptchaObj] = useState({
        captcha: '',
        captchaNo: '',
    });

    // 用于登录
    const onLoginFinish = useCallback(
        async (values) => {
            clearStorage();
            try {
                //当前没有加密，临时方案
                const { userName, password } = values;
                const [error, loginData] = await to(
                    login({
                        ...captchaObj,
                        captcha: form.getFieldValue('captcha'),
                        userName: userName.trim(),
                        password: md5(password.trim()),
                    }),
                );
                if (error) {
                    console.log(error);
                }

                const { token } = loginData;
                setStorage({ token: token.accessToken });
                const { userInfo, frontCodeList, menuList: originMenuList } = await getUserBaseInfo({});
                const realMenuList = getRealMenuList(userInfo.adminFlag ? getFrontCodeListForAdmin() : frontCodeList, originMenuList);
                const targetPath = getFirstPagePath(realMenuList);
                // 存储登录的一般信息
                setStorage({ userInfo, frontCodeList, originMenuList, menuList: realMenuList });
                // 更新路由
                uiData.updateFrontCodeList(frontCodeList);
                navigate(targetPath || '/auth');
            } catch (error) {
                console.error(`login error - ${JSON.stringify(error)}----${error}`);
                // 自定更新验证码
                initCaptcha();
            }
        },
        [captchaObj],
    );

    const initCaptcha = async () => {
        const data = await captcha({});
        setCaptchaObj({
            captcha: data.captcha,
            captchaNo: data.captchaNo,
        });
        setCaptchaImg('data:image/jpeg;base64,' + data.img);
    };

    useEffect(() => {
        initCaptcha();
    }, []);

    return { initCaptcha, captchaImg, onLoginFinish };
}
export default useLogin;
